<template>
  <div>
    <el-form ref="restForm" :model="rest" label-width="80px" :rules="rules">
      <el-form-item label="住户姓名" prop="name">
        <el-input v-model="rest.name"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input type="number" v-model.number="rest.age"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="rest.gender"
          placeholder="请选择"
          style="width: 25%"
        >
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="小区位置" prop="plotName">
        <el-select
          v-model="rest.plotName"
          placeholder="请选择"
          style="width: 25%"
        >
          <el-option
            v-for="area in areaList"
            :key="area._id"
            :label="area.administer"
            :value="area.administer"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号" prop="id_number">
        <el-input v-model="rest.id_number"></el-input>
      </el-form-item>
      <el-form-item label="电话号" prop="phone">
        <el-input v-model="rest.phone"></el-input>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input v-model="rest.address"></el-input>
      </el-form-item>
      <el-form-item label="微信" prop="vx">
        <el-input v-model="rest.vx"></el-input>
      </el-form-item>
      <el-form-item label="照片" prop="pictures">
        <el-upload
          :action="baseApi + '/img/upload'"
          list-type="picture-card"
          :auto-upload="true"
          :file-list="fileList"
          name="image"
          accept="image/*"
          :on-change="handleChange"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
              >
                <i class="el-icon-download"></i>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <!-- <el-form-item label="备注" prop="note">
        <vue-tinymce v-model="rest.note" :setting="setting"></vue-tinymce>
      </el-form-item> -->
      <el-form-item>
        <el-button v-if="!a" type="primary" @click="onSubmit('restForm')"
          >立即创建</el-button
        >
        <el-button v-if="a" type="primary" @click="updateSubmit('restForm')"
          >更新</el-button
        >
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import areaApi from "@/api/area"; //获取区域数据
import restApi from "@/api/rest";
export default {
  data() {
    var validatePhone = (rule, value, callback) => {
      value = value.trim();
      // 提高性能，判断value是否有值有值返回长度
      const length = value && value.length;
      const pwdReg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (value === "") {
        callback(new Error("请输入账号"));
      } else if (!pwdReg.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    var validateIdNumber = (rule, value, callback) => {
      value = value.trim();
      const _IDRe18 =
        /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      const _IDre15 =
        /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;
      if (_IDRe18.test(value) || _IDre15.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的身份证号码"));
      }
    };
    return {
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
        gender: [{ required: true, message: "请选择性别", trigger: "tigger" }],
        plotName: [
          { required: true, message: "请输入小区位置", trigger: "tigger" },
        ],
        id_number: [
          {
            required: true,
            message: "请输入身份证号",
            validator: validateIdNumber,
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            validator: validatePhone,
            message: "请输入手机号",
            trigger: "blur",
          },
        ],
        vx: [{ required: true, message: "请输入微信", trigger: "blur" }],
      },
      // setting: {
      //   //去除文件栏
      //   menubar: false,
      //   //定义工具栏
      //   toolbar:
      //     "undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat |",
      //   toolbar_drawer: "sliding",
      //   quickbars_selection_toolbar:
      //     "removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor",
      //   //工具栏模块
      //   plugins: "link image media table lists fullscreen quickbars imagetools",
      //   language: "zh_CN", //本地化设置
      //   height: 350,
      // },
      a: Boolean,
      dialogImageUrl: "",
      disabled: false, //按钮是否显示
      fileList: [],
      baseUrl: process.env.VUE_APP_SERVICE_URL,
      baseApi: process.env.VUE_APP_BASE_API,
      dialogVisible: false,
      areaList: [],
      rest: {
        name: "",
        age: "",
        gender: "",
        plotName: "",
        id_number: "",
        phone: "",
        address: "",
        vx: "",
        pictures: "",
        note: "",
      },
    };
  },

  components: {},
  mounted() {
    this.getAreaList();
    this.getRest();
    if (this.$route.params._id == -1) {
      this.a = false;
    } else {
      this.a = true;
    }
  },
  methods: {
    // 更新用户数据
    updateSubmit() {
      this.rest._id = this.$route.params._id;
      restApi.update(this.rest).then((response) => {
        const res = response.data;
        // console.log(res);
        if (res.status == 0) {
          this.$message({
            message: "更新成功",
            type: "success",
          });
          this.$router.replace("/rest");
        } else {
          this.$message({
            message: "更新失败",
            type: "warning",
          });
        }
      });
    },
    // 获取编辑住户
    getRest() {
      console.log(this.$route);
      const { _id } = this.$route.params;
      // console.log(_id);
      if (_id == -1) {
        return false;
      }
      restApi.getRest(_id).then((response) => {
        const res = response.data;
        console.log(res);
        if (res.status == 0) {
          this.rest = res.data;
          const { pictures } = res.data;
          // console.log(pictures);
          if (pictures && pictures.length > 0) {
            this.fileList = pictures.map((img, index) => ({
              name: img,
              url: this.baseUrl + "/upload/" + img,
            }));
          }
          console.log("a", this.fileList);
        }
      });
    },
    //图片改变
    handleChange(file, fileList) {
      // console.log(fileList); //存储图片数组
      // console.log(1, file); //当前存储图片
      if (file.status == "success") {
        const result = file.response;
        // console.log(result)
        if (result.status == 0) {
          const { name, url } = result.data;
          file = fileList[fileList.length - 1];
          file.name = name;
          file.url = url;
        }
      }
      this.fileList = fileList;
      console.log(this.fileList);
      // this.fileList = this.getImgs();
      // console.log(this.fileList);
    },
    //获取所有已上传图片的文件名的数组
    getImgs() {
      return this.fileList.map((file) => file.name);
    },
    // 删除图片
    handleRemove(file) {
      console.log(file.name);
      console.log(this.fileList);
      restApi.restDeleteImg(file.name).then((response) => {
        const res = response.data;
        if (res.status == 0) {
          // console.log(this.fileList.indexOf(file));
          this.fileList.splice(this.fileList.indexOf(file), 1);
        }
      });
    },
    // 查看大图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    // =========================
    getAreaList() {
      areaApi.getareasList().then((response) => {
        const res = response.data;
        if (res.status == 0) {
          this.areaList = res.data;
          // console.log(this.areaList);
        } else {
          this.$message({
            message: "获取失败",
            type: "warning",
          });
        }
      });
    },
    // 创建住户
    onSubmit(resForm) {
      this.$refs[resForm].validate((valid) => {
        if (valid) {
          this.rest.pictures = this.getImgs();
          restApi.addRest(this.rest).then((response) => {
            const res = response.data;
            if (res.status == 0) {
              this.$router.replace("/rest");
            }
          });
          // console.log(this.rest);
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.el-input {
  width: 25%;
}
</style>